<script setup lang="ts" name="aiNdeProcedure">
import { useElementSize } from '@vueuse/core';
import {
  deleteByConversationIdStartsWithUserName,
  getMemoryListByUsername,
  getMemoryByChatId,
  getPtProcedure,
  useLoginUserStore
} from '@/index';
import type { AIProcedureRequest, AiPTProcedure } from '@/index.d';
import { dayjs } from 'element-plus';
import { useRequest } from 'vue-request';
import PtProcedure from './PtProcedure.vue';
const scrollbarContainerRef1 = useTemplateRef('scrollbarContainerRef1');
const scrollbarContainerRef2 = useTemplateRef('scrollbarContainerRef2');
const scrollbarRef1 = useTemplateRef('scrollbarRef1');
const { height: height1 } = useElementSize(scrollbarContainerRef1);
const { height: height2 } = useElementSize(scrollbarContainerRef2);

const { loginUser } = useLoginUserStore();

const aiRequest = reactive<AIProcedureRequest>({
  model: 'qwen-max',
  userMessage: '',
  temperature: 0.8,
  username: useLoginUserStore().loginUser.username as string,
  conversationId: '',
  response: '',
  aiLoading: false,
  documentIndex: 'sdw',
  method: 'PT'
});

watch(
  () => aiRequest.method,
  () => {
    aiRequest.conversationId =
      loginUser.username + '-' + aiRequest.method + '-' + dayjs().toISOString();
  },
  {
    immediate: true
  }
);

const title = computed(() => {
  return '提示词：' + aiRequest.userMessage;
});

const ptProcedure = reactive<AiPTProcedure>({
  temperatureUp: 0,
  temperatureDown: 0,
  penetrationDwellTimeUp: 0,
  penetrationDwellTimeDown: 0,
  penetrationSetManufacturer: '',
  penetrationName: '',
  cleanerName: '',
  developerName: '',
  writerName: '',
  reviewerName: '',
  approverName: '',
  currentDate: '',
  acceptStandard: '',
  documentReference: 0,
  documentRevision: 0
});

const startGpt = async (event: Event) => {
  event.preventDefault();
  await getPtProcedure(aiRequest, ptProcedure);
  getMemoryListByUsernameRun();
  getMemoryByChatIdRun();
};

const {
  data: getMemoryListByUsernameData,
  run: getMemoryListByUsernameRun,
  loading: getMemoryListByUsernameLoaing
} = useRequest(() => getMemoryListByUsername(aiRequest.method));

const {
  data: getMemoryByChatIdData,
  run: getMemoryByChatIdRun,
  loading: getMemoryByChatIdLoaing
} = useRequest(() => getMemoryByChatId(aiRequest.conversationId));

const newConversation = () => {
  aiRequest.conversationId =
    loginUser.username + '-' + aiRequest.method + '-' + dayjs().toISOString();
};

const changeConversationId = (conversationId: string) => {
  aiRequest.conversationId = conversationId;
};

const clearHistory = async () => {
  await deleteByConversationIdStartsWithUserName();
  getMemoryListByUsernameRun();
  aiRequest.conversationId =
    loginUser.username + '-' + aiRequest.method + '-' + dayjs().toISOString();
};

watch(
  () => aiRequest.conversationId,
  () => {
    getMemoryByChatIdRun();
  }
);
</script>
<template>
  <el-row class="ai-container" :gutter="1">
    <el-col :span="19">
      <el-card>
        <template #header>{{ title }}</template>
        <template #default>
          <div
            ref="scrollbarContainerRef1"
            class="scrollbar-container"
            v-loading="getMemoryByChatIdLoaing"
          >
            <el-scrollbar ref="scrollbarRef1" :height="height1">
              <template v-for="value in getMemoryByChatIdData">
                <div class="scrollbar-container-title" v-if="value.type === 'USER'">
                  {{ value.content }}
                </div>
                <div class="scrollbar-container-content" v-if="value.type === 'ASSISTANT'">
                  <PtProcedure :pt-procedure="JSON.parse(value.content)" />
                </div>
              </template>
            </el-scrollbar>
          </div>
        </template>
        <template #footer>
          <el-form :model="aiRequest">
            <el-form-item label="方法：" for="model" style="width: 100%">
              <el-radio-group v-model="aiRequest.method">
                <el-radio
                  v-for="item in ['PT', 'MT', 'UT', 'RT']"
                  :key="item"
                  :value="item"
                  :label="item"
                  :disabled="aiRequest.aiLoading"
                />
              </el-radio-group>
            </el-form-item>
            <el-form-item label="输入：" for="userMessage" style="width: 100%">
              <el-input
                v-model="aiRequest.userMessage"
                :readonly="aiRequest.aiLoading"
                @keydown.enter="startGpt"
              />
            </el-form-item>

            <el-form-item style="width: 100%">
              <el-button
                type="success"
                style="width: 100%"
                @click="startGpt"
                :loading="aiRequest.aiLoading"
              >
                发送
              </el-button>
            </el-form-item>
          </el-form>
        </template>
      </el-card>
    </el-col>
    <el-col :span="5">
      <el-card>
        <template #header>
          <el-button type="primary" @click="newConversation">新的对话</el-button>
          <el-button
            type="warning"
            @click="clearHistory"
            v-if="getMemoryListByUsernameData?.length"
          >
            清空历史
          </el-button>
        </template>
        <template #default>
          <div ref="scrollbarContainerRef2" class="scrollbar-container">
            <el-scrollbar :height="height2">
              <div class="scrollbar-container-content2" v-loading="getMemoryListByUsernameLoaing">
                <el-link
                  v-for="value in getMemoryListByUsernameData"
                  @click="changeConversationId(value.conversationId)"
                >
                  <el-text truncated>
                    {{ value.timestamp.slice(0, 10) + '：' + value.content }}
                  </el-text>
                </el-link>
              </div>
            </el-scrollbar>
          </div>
        </template>
      </el-card>
    </el-col>
  </el-row>
</template>

<style scoped lang="scss">
.ai-container {
  height: 100%;
  width: 100%;
  padding: 5px;
  display: flex;
  flex-direction: row;

  .el-card {
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;
    :deep(.el-card__body) {
      flex: 1;
      padding: 0;
      .scrollbar-container {
        height: 100%;
        .scrollbar-container-title {
          color: red;
          font-weight: bolder;
          line-height: 2rem;
          padding: 20px 30px;
        }
        .scrollbar-container-content {
          line-height: 2rem;
          padding: 20px 30px;
        }

        .scrollbar-container-content2 {
          padding: 5px;
          line-height: 2rem;
          display: flex;
          flex-direction: column;
          .el-link {
            justify-content: flex-start;
          }
        }
      }
    }
  }
}
</style>
